import { Modal, Form, Input, message, Table } from 'antd'
const FormItem = Form.Item;
import { connect } from 'umi';
import ContentLayout from '@/layouts/ContentLayout'
import { useEffect, useState } from 'react';
import ArrayUtils from '@/utils/ArrayUtils'
import { PROJECT_QA_CASE_SCENE } from '@/consts/project'
import UserBrief from '@/components/UserBrief'
import { pageQaCase } from '@/services/project/qaCase'
import { pageCasePlan, updateCaseIds } from '@/services/project/casePlan';

const QaCasePlanRelCaseEditModal = (props) => {

    const {
        projectId,
        projectQaItemId,
        projectQaCasePlanId,
        visible,
        onCancel,
        onSaveSuccess,
        casePlanDetailList,
        dispatch,
    } = props;

    const [qaCasePage, setQaCasePage] = useState();
    const [qaCasePageLoading, setQaCasePageLoading] = useState(false);

    const [selectCase, setSelectCase] = useState([])
    const [selectCaseIsExectue, setSelectCaseIsExectue] = useState({})
    const [params, setParams] = useState({

    })

    useEffect(() => {
        if (visible) {
            onParamChange();
        }
        if (visible && casePlanDetailList) {
            let selectCaseIds = []
            let selectCaseIsExectueMap = {}
            for (let index in casePlanDetailList) {
                let casePlanDetail = casePlanDetailList[index];
                selectCaseIds.push(casePlanDetail.projectQaCaseId);
                if (casePlanDetail.isExecute) {
                    selectCaseIsExectueMap[casePlanDetail.projectQaCaseId] = true;
                }
            }
            setSelectCase(selectCaseIds);
            setSelectCaseIsExectue(selectCaseIsExectueMap);
        }
    }, [visible,casePlanDetailList])

    const onParamChange = (param) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        queryQaCasePage(newParams)
    }

    const queryQaCasePage = (queryParams) => {
        setQaCasePageLoading(true)
        pageQaCase(projectId, projectQaItemId, (queryParams || params))
            .then((result) => {
                if (result.success) {
                    setQaCasePage(result.data)
                    setQaCasePageLoading(false)
                }
            })
    }

    const onSelectChange = (selectedRowKeys) => {
        let tempSelectCase = selectCase ? [...selectCase] : [];
        for (let index in selectedRowKeys) {
            if (tempSelectCase.indexOf(selectedRowKeys[index]) < 0) {
                tempSelectCase.push(selectedRowKeys[index])
            }
        }
        setSelectCase(tempSelectCase)
    }

    const onSelectOne = (record, selected, selectedRows, nativeEvent) => {
        if (!selected) {
            ArrayUtils.remove(selectCase,record.id)
            setSelectCase(selectCase)
        }
    }

    const saveQACasePlanRelCase = () => {
        updateCaseIds(projectId, projectQaItemId, projectQaCasePlanId, selectCase)
            .then(({ success }) => {
                if (success) {
                    message.success("保存成功");
                    if (onSaveSuccess) {
                        onSaveSuccess()
                    }
                }
            })
    }

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: "20%",
            fixed: 'left',
            ellipsis: true,
            sorter: (a, b) => a.name.localeCompare(b.name),
        },

        {
            title: '阶段类型',
            dataIndex: 'scene',
            key: 'scene',
            width: "72px",
            render: (text, record) => PROJECT_QA_CASE_SCENE[record.scene].name,
        },
        {
            title: '模块',
            dataIndex: 'moduleName',
            ellipsis: true,
            key: 'module_name',
        },
        {
            title: '负责人',
            dataIndex: 'userId',
            ellipsis: true,
            key: 'userId',
            width: "14%",
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        }
    ]

    const queryItems = [
        {
            name: "inScene",
            label: "阶段类型",
            isMain: true,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(PROJECT_QA_CASE_SCENE).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "likeName",
            label: "名称",
            span: 12,
            isMain: false,
            type: "input",
        },
        {
            name: "inUserId",
            label: "负责人",
            isMain: false,
            span: 12,
            type: "input",
        }
    ]



    return (<Modal
        visible={visible}
        closable
        title={"新增用例执行"}
        onCancel={onCancel}
        onOk={() => {
            saveQACasePlanRelCase();
        }}
        width="60%"
        destroyOnClose
        okText={"确认"}
        cancelText={"取消"}
    >
        <ContentLayout
            queryItems={queryItems}
            onQueryChange={(params) => {
                onParamChange(params)
            }}
            style={{ minWidth: "100%" }}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    rowSelection={{
                        selectedRowKeys: selectCase,
                        onChange: onSelectChange,
                        onSelect: onSelectOne,
                        getCheckboxProps: (record) => {
                            return {
                                disabled: selectCaseIsExectue[record.id]
                            }
                        }
                    }}
                    columns={tableColumns}
                    loading={qaCasePageLoading}
                    rowKey="id"
                    dataSource={qaCasePage && qaCasePage.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: qaCasePage && qaCasePage.count,
                        current: qaCasePage && qaCasePage.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                            }
                        }
                    }}
                >
                </Table>
            }
        />
    </Modal>)
}

export default connect(({ casePlan, loading }) => ({
}))(QaCasePlanRelCaseEditModal);
